from qcloud_cos import CosConfig, CosS3Client
import os
from flask import has_request_context


def get_cos_client(tenant_id=None):
    """获取当前租户的COS客户端"""
    try:
        # 尝试使用动态租户配置
        if has_request_context() or tenant_id:
            from app.services.tenant_config_service import get_tenant_config

            # 如果传入了tenant_id，需要特殊处理
            if tenant_id:
                from app.models.tenant_config import TenantConfigService, ConfigTypes
                secret_id = TenantConfigService.get_config(tenant_id, ConfigTypes.TCOS, 'secret_id')
                secret_key = TenantConfigService.get_config(tenant_id, ConfigTypes.TCOS, 'secret_key')
                region = TenantConfigService.get_config(tenant_id, ConfigTypes.TCOS, 'region')
                bucket = TenantConfigService.get_config(tenant_id, ConfigTypes.TCOS, 'bucket')
            else:
                tenant_config = get_tenant_config()
                tcos_config = tenant_config.get_tcos_config()
                secret_id = tcos_config.get('secret_id')
                secret_key = tcos_config.get('secret_key')
                region = tcos_config.get('region')
                bucket = tcos_config.get('bucket')

            # 如果租户配置完整，使用租户配置
            if all([secret_id, secret_key, region, bucket]):
                config = CosConfig(
                    Region=region,
                    SecretId=secret_id,
                    SecretKey=secret_key,
                    Token=None,
                    Scheme='https'
                )
                return CosS3Client(config), bucket, region
    except Exception as e:
        # 如果获取租户配置失败，使用环境变量作为后备
        from flask import current_app
        if current_app:
            current_app.logger.debug(f"获取租户COS配置失败，使用环境变量: {str(e)}")

